import { createRouter, createWebHistory } from 'vue-router'
import bjsdk from '@/libs/beta-jsdk'
import { backToHistoryBtn } from '@/utils'

// 自动注入路由，页面无需引入
const files = require.context('.', false, /\.js$/)
let routes = [
	{
		path: '/',
		meta: {
			title: '',
		},
		redirect: {
			path: '/home',
		},
	},
]
files.keys().forEach((fileName) => {
	if (fileName === './index.js') return
	routes = routes.concat(files(fileName).default)
})
const router = createRouter({
	history: createWebHistory(
		(/(\/prp\/[^/]+)/i.test(location.pathname) ? RegExp.$1 : '') +
			'/BetaCS.CustBindH5'
	),
	routes,
	// 清除路由缓存【to.meta.behavior---true时候清除，pubHome页面使用。不影响其它页面】
	scrollBehavior(to, from, savedPosition) {
		// if (to.meta.behavior) {
		// 	return savedPosition
		// }
	},
})

router.beforeEach((to, from, next) => {
	window._routerFrom = from
	window._routerTo = to
	//判断是否有标题
	if (to.meta.title) {
		document.title = to.meta.title
	} else {
		document.title = ''
	}
	next()
})

router.afterEach((to, from) => {
	backToHistoryBtn(bjsdk)
})

export default router
